package org.example.demo2.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class FileUploadController {
    @Value("${web.upload-path}")
    private String path;
    @PostMapping("/uploadFile")
    public String upload(@RequestParam MultipartFile file, HttpServletRequest request){
        if (!file.isEmpty()){
            File file1 = new File(path);
            if (!file1.exists()){
                file1.mkdir();
            }
            String originalFilename = file.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            if (file.getSize()>1024000) {
                throw  new RuntimeException("文件过大!");
            }else if (substring.equalsIgnoreCase(".gif")||
                    substring.equalsIgnoreCase(".jpg")||
                    substring.equalsIgnoreCase(".png")||
                    substring.equalsIgnoreCase(".jpeg")) {
                String new_file = UUID.randomUUID() + substring;
                File file2 = new File(path  + new_file);
                try {
                    file.transferTo(file2);
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new RuntimeException("文件上传错误!!");
                }
            } else {
                throw  new RuntimeException("文件格式错误!!");
            }
        }
        return "success";
    }
}
